package com.pj.util;

import java.util.Map;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 *  JSON 转换器
 * 
 * @author click33
 * @since: 2022-11-24
 */
public class JsonUtil {

	/**
	 * 底层 Mapper 对象 
	 */
	public static ObjectMapper objectMapper = new ObjectMapper();

	/**
	 * 将任意对象转换为 json 字符串 
	 * 
	 * @param obj 对象 
	 * @return 转换后的 json 字符串
	 */
	public static String toJsonString(Object obj) {
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 将 json 字符串解析为 Map
	 */
	public static Map<String, Object> parseJsonToMap(String jsonStr) {
		try {
			@SuppressWarnings("unchecked")
			Map<String, Object> map = objectMapper.readValue(jsonStr, Map.class);
			return map;
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 将任意类型转化为指定类型 
	 */
	public static <T>T parseObjectToModel(Object obj, Class<T> cs) {
		if(obj == null) {
			return null;
		}
		String jsonStr = toJsonString(obj);
		try {
			return objectMapper.readValue(jsonStr, cs);
		} catch (JsonProcessingException e) {
			throw new RuntimeException(e);
		}
	}

}
